/*
 * Copyright 2011 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.abcsolutions.g5.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import de.abcsolutions.g5.base.event.A_HasListeners;
import de.abcsolutions.g5.base.event.I_Listener;

/**
 * @author Michael Nitsche
 * 01.03.2011	Created
 *
 * Listen for incoming UDP-Packets
 */
public class UDP_Server extends A_HasListeners {

	private enum EVENT { EXCEPTION, DATA };
	private Thread daemon=null;
	private final DatagramSocket socket;


	public UDP_Server(int port) throws SocketException {
		this.socket=new DatagramSocket(port);
	}


	public void start() {
		this.daemon=new Thread() {
			public void run() {
				try {
					while(!this.isInterrupted()) {
						DatagramPacket packet = new DatagramPacket( new byte[65535], 65535);
						try {
							socket.setSoTimeout(1000);
							socket.receive( packet );
						}
						catch(SocketTimeoutException e) {
							return;
						}
						catch(IOException e) {
							listenerStart(EVENT.EXCEPTION, e);
							System.err.println(e);
						}
						listenerStart(EVENT.DATA, packet);
					}
				}
				catch(Throwable t) {
					System.err.println(t);
				}
			}
		};
		this.daemon.setDaemon(true);
		this.daemon.start();
	}

	public void stop() {
		this.daemon.interrupt();
		try {
			this.socket.setSoTimeout(1);
			this.socket.disconnect();
			this.socket.close();
		}
		catch(SocketException e) {
			System.err.println(e);
		}
		this.daemon=null;
	}

	public void send(byte[] ip, int port, byte[] data) throws IOException {
		send(InetAddress.getByAddress(ip), port, data);
	}

	public void send(String address, int port, byte[] data) throws IOException {
		send(InetAddress.getByName(address), port, data);
	}

	public void send(InetAddress address, int port, byte[] data) throws IOException {
		DatagramPacket packet=new DatagramPacket(data, 0, data.length, address, port);
		send(packet);
	}

	public void send(DatagramPacket packet) throws IOException {
		socket.send(packet);
	}

	public void addDataListener(I_Listener<DatagramPacket> z) {
		this.listenerAdd(EVENT.DATA, z);
	}

	public void addExceptionListener(I_Listener<Exception> z) {
		this.listenerAdd(EVENT.EXCEPTION, z);
	}

	public boolean isRunning() {
		return this.daemon!=null && this.socket!=null && this.socket.isBound() && !this.socket.isClosed(); //TODO Test!
	}

}
